using UnityEngine;
using System.Collections;

public class HSController : MonoBehaviour
{
	public static bool sPostScore = false;
	public static int sScore = 20;

	private string secretKey = "key_for_backdraft_tavu";
	// Edit this value and make sure it's the same as the one stored on the server
	public string addScoreURL = "http://thorodinson.free.fr/Unity/Backdraft/php_scripts/addscore.php?";
	//be sure to add a ? to your url
	public string highscoreURL = "http://thorodinson.free.fr/Unity/Backdraft/php_scripts/display.php";
	
	public GameObject NameEntryRoot;
	public GameObject NameEntryGuiText;
	public GameObject DisplayEntryRoot;
	
	public int numberOfScore { get { return nbScores; } }
	public int offset { get { return mOffset; } set { mOffset = value;} }
	
	private int nbScores = 0;
	private int mOffset = 0;
	
	private bool mEntringName = false;

	IEnumerator Start ()
	{
		if (sPostScore) 
		{
			NameEntryRoot.SetActiveRecursively(true);
			DisplayEntryRoot.SetActiveRecursively(false);
			yield return StartCoroutine(AskForName());
			DisplayEntryRoot.SetActiveRecursively(true);
			
			
		} 
		
		NameEntryRoot.SetActiveRecursively(false);
		
		StartCoroutine(GetScores ());
	}
	
	void Update()
	{
		if(mEntringName)
		{
			foreach (char c in Input.inputString) 
			{
	            if (c == "\b"[0])
				{
	                if (NameEntryGuiText.guiText.text.Length != 0)
					{
	                    NameEntryGuiText.guiText.text = NameEntryGuiText.guiText.text.Substring(0, NameEntryGuiText.guiText.text.Length - 1);
					}
				}
	            else
				{
	                if (c == "\n"[0] || c == "\r"[0])
					{
	                    mEntringName = false;
					}
	                else
					{
						if(System.Char.IsLetterOrDigit(c))
	                    	NameEntryGuiText.guiText.text += c;
					}
				}
	        }
		}
	}
	
	public void RetrieveScore()
	{
		StartCoroutine (GetScores ());
	}
	
	IEnumerator AskForName()
	{
		NameEntryGuiText.guiText.text = "";
		mEntringName = true;
		
		while(mEntringName)
		{
			yield return new WaitForSeconds(0.1f);
		}
		
		yield return StartCoroutine(PostScores(NameEntryGuiText.guiText.text, sScore));
	}

	// remember to use StartCoroutine when calling this function!
	IEnumerator PostScores (string name, int score)
	{
		//This connects to a server side php script that will add the name and score to a MySQL DB.
		// Supply it with a string representing the players name and the players score.
		string hash = MD5Test.MD5Sum (name + score + secretKey);
		
		string post_url = addScoreURL + "name=" + WWW.EscapeURL (name) + "&score=" + score + "&hash=" + hash;
		
		// Post the URL to the site and create a download object to get the result.
		WWW hs_post = new WWW (post_url);
		yield return hs_post;
		// Wait until the download is done
		if (hs_post.error != null) {
			print ("There was an error posting the high score: " + hs_post.error);
		}
		else
		{
			WWW getPos = new WWW ("http://thorodinson.free.fr/Unity/Backdraft/php_scripts/getPosition.php?name="+name);
			yield return getPos;
			
			int lPos = System.Convert.ToInt32(getPos.text);
			offset = lPos/10 * 10;
		}
	}

	// Get the scores from the MySQL DB to display in a GUIText.
	// remember to use StartCoroutine when calling this function!
	IEnumerator GetScores ()
	{
		gameObject.guiText.text = "Loading Scores";
		WWW hs_get = new WWW (highscoreURL+"?offset="+mOffset);
		yield return hs_get;
		
		if (hs_get.error != null) {
			print ("There was an error getting the high score: " + hs_get.error);
		} else {
			gameObject.guiText.text = processText(hs_get.text);
			// this is a GUIText that will display the scores in game.
		}
	}
	
	
	private string processText(string pText)
	{
		string lReturn = "";
		
		string[] lLineSplit = pText.Split('\n');
		
		nbScores = System.Convert.ToInt32(lLineSplit[0]);
		
		for(int i = 1; i < lLineSplit.Length; i++)
		{
			string[] lSplitTab = lLineSplit[i].Split('\t');
			
			if(lSplitTab.Length >= 2)
			{
				lReturn += (mOffset + i) + " - " + lSplitTab[0] + " : " + lSplitTab[1] + "\n\n";
			}
		}
		
		return lReturn;
	}
	
}


public class MD5Test : MonoBehaviour
{

	static public string MD5Sum (string strToEncrypt)
	{
		
		
		
		System.Text.UTF8Encoding ue = new System.Text.UTF8Encoding ();
		
		
		
		byte[] bytes = ue.GetBytes (strToEncrypt);
		
		
		
		
		
		
		
		// encrypt bytes
		
		
		
		System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider ();
		
		
		
		byte[] hashBytes = md5.ComputeHash (bytes);
		
		
		
		
		
		
		
		// Convert the encrypted bytes back to a string (base 16)
		
		
		
		string hashString = "";
		
		
		
		
		
		
		
		
		
		
		for (int i = 0; i < hashBytes.Length; i++) {
			
			hashString += System.Convert.ToString (hashBytes[i], 16).PadLeft (2, '0');
			
		}
		return hashString.PadLeft (32, '0');
	}
}
